/*
 * @Author: Yuluo 568055454@qq.com
 * @Date: 2023年06月16日 21:36:25
 * @LastEditors: Yuluo 568055454@qq.com
 * @LastEditTime: 2023年07月16日 03:55:44
 * @FilePath: \Mood-Blog-System\back\db.js
 * @Description: 数据库连接文件
 * Copyright (c) 2023 by Yuluo, All Rights Reserved. 
 */

const mongoose = require('mongoose');
const { db } = require('./config');
const logger = require('./log4');
const { convertToString, toJSON } = require('./util/core');
const { logTemplate } = require('./util/log4js');
const connectUrl = `mongodb://${db.user}:${db.password}@${db.host}:${db.port}/${db.name}?authSource=admin`
module.exports = {
    mongoose,
    db: mongoose.connection,
    install: async function (app) {
        mongoose.connect(connectUrl, db.opts).then(() => {
            console.log('Connected to database successfully.');
            mongoose.Promise = global.Promise;
            // 注册中间件，在每次执行语句前记录 SQL 到日志文件
            mongoose.set('debug', true)
            // mongoose.set('debug', function (collectionName, method, query, doc) {
            //     logger('db').info(logTemplate({
            //         message: '数据库操作',
            //         data: { collectionName, method, query, doc }
            //     }));
            //     console.info(`Mongoose: ${collectionName}.${method}(${convertToString(query)})`);
            // });
            require('require-all')(__dirname + '/models');
        }).catch((error) => {
            console.log('Error connecting to database', error)
        });
    }
};
